package performance;


import java.sql.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 多客户端多线程测数据库性能测试 <br/>
 * 不同库同表
 *
 * @author yancheng11334
 *
 */
public class TpsDataExecuteTest extends BaseTpsTest {

    private static int INSERT_SQL_NUM = 2000;


    private static final String  STR_LONG_TEXT = "疯似的飞三番四复三番四复三番四复收发室圣克拉拉开发放到沙发上发撒旦发生发生发撒旦发撒发撒旦发撒发生飞洒";

    private static final AtomicInteger insertCount = new AtomicInteger(0);


    /**
     * 测试一定时间内的插入SQL性能<br/>
     * 随机生成主键ID，可以多个客户端运行
     * @throws Exception
     */
    public void doDataExe() throws Exception {
        Connection conn = null;
        PreparedStatement pStmt = null;
        try {
            //测试长连接(1个线程生命周期只创建一次连接)
            conn = getConnection();
            conn.setAutoCommit(false);
            pStmt = conn.prepareStatement("insert into score(id,name,score,course) values(?,?,?,?)");
            pStmt.setQueryTimeout(0);
            int r=0;
            int count=0;
            while ((r=insertCount.getAndIncrement()) < INSERT_SQL_NUM) {
                long id = r;
                count++;
                long temp = (long)(Math.random()*500000);
                pStmt.setLong(1, id);
                pStmt.setString(2, "yc"+temp);
                pStmt.setInt(3, 60);
                pStmt.setString(4, temp+STR_LONG_TEXT);
//                    pStmt.executeUpdate();
                pStmt.addBatch();
                if(count%1000==0){
                    pStmt.executeBatch();
                }
            }
            pStmt.executeBatch();
            conn.commit();
        } finally {
            close(pStmt);
            close(conn);
        }
    }

}
